import React, {Component,} from 'react';
import {connect} from 'dva';
import {formatMessage} from 'umi-plugin-react/locale';
import {Button, InputItem, Toast} from 'antd-mobile';
import {Alert, Form, Modal,} from 'antd';
import Login from '@/components/Login';
import styles from './Login.less';
import {removeAuthorization, saveAuthorization, saveMenus, saveOrg, saveRoles, saveUser,} from '@/utils/bwdautil';
import { encode } from '@/utils/AesUtil';

const FormItem = Form.Item;
const {Tab, UserName, Password, Mobile, Captcha, Submit, ImageVerifyCode,} = Login;



@connect(({login, loading}) => ({
  login,
  submitting: loading.effects['login/login'],
}))
class LoginPage extends Component {
  state = {
    type: 'account',
    autoLogin: false,
    verifyCodeUuid: '',
    imageBase64: '',
    isNeedImageCode: false,
    verionData: {},
    pwdInutType:'text',
  };


  /**
   *获取认证方式，内部认证，外部认证，url，
   * */
  getOauthType = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'login/getOauthType',
    });

  };


  onTabChange = type => {
    this.setState({type});
  };

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      this.loginForm.validateFields(['mobile'], {}, (err, values) => {
        if (err) {
          reject(err);
        } else {
          const {dispatch} = this.props;
          dispatch({
            type: 'login/getCaptcha',
            payload: values.mobile,
          })
            .then(resolve)
            .catch(reject);
        }
      });
    });

  /**
   *
   * **/
  onGetImgCode = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'login/getImageCaptcha',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({imageBase64: res.data.imageBase64, verifyCodeUuid: res.data.verifyCodeUuid});
        } else {
          this.setState({imageBase64: "",verifyCodeUuid:''});
        }
      },
    })
  }


  handleSubmit =async (err, values) => {
    const {type,verifyCodeUuid} = this.state;
    let ecnPwd =await encode(values.password);
    if (!err) {
      const {dispatch} = this.props;

      dispatch({
        type: 'login/login',
        payload: {
          username: values.userCode,
          verifyCode: values.imageVerifyCode,
          verifyCodeUuid: verifyCodeUuid,
          password: ecnPwd,
          // password: values.password,
        },
        callback: (res) => {
          //需要验证码
          if (res.result == "fail") {
            /*  message.success(res.msg);*/
            Modal.error({title: '操作失败', content: res.msg});
          }

          if (res.rescode == 203) {
            this.setState({isNeedImageCode: true});
            this.onGetImgCode();
          }
        },
      });
    }
  };


  componentDidMount() {
    removeAuthorization();
    this.getOauthType();
    this.infoList();
    this.pwdrule();
  }

  pwdrule = data => {
    const {dispatch} = this.props;
    dispatch({
      type: 'user/pwdruleF',
      callback: (res) => {
        if (res.result == "ok" && res.data.enableVerifiCode == 1) {
          this.setState({isNeedImageCode: true});
        }
      },
    });
  }

  infoList() {
    const {dispatch} = this.props;
    dispatch({
      type: 'login/infoList',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            verionData: res.data,
          })
        }
      },
    });
  }

  downloadBwdaClient() {
    window.open("/DSRS-Client.exe", "_self");
  }

  renderMessage = content => (
    <Alert style={{marginBottom: 24}} message={content} type="error" showIcon/>
  );
  changePwdInputType=()=>{
    this.setState({
      pwdInutType: 'password',
    })
  }

  render() {
    const {login, submitting,} = this.props;
    const {type, imageBase64, isNeedImageCode,verionData,pwdInutType} = this.state;
    return (
      <div className={styles.main}>
        <Login
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={form => {
            this.loginForm = form;
          }}
        >
          {/*登录名登录*/}
          <Tab key="account" tab={formatMessage({id: 'app.login.tab-login-credentials'})}>
            {login.status === 'error' &&
            login.type === 'account' &&
            !submitting &&
            this.renderMessage('登录名或密码错误')}
            <UserName
            name="userCode"
            placeholder="登录名"
            autoComplete="off"
            rules={[
              {
                required: true,
                message: "请输入登录名",
              },
            ]}
          />

            <Password
              name="password"
              pwdInutType={pwdInutType}
              placeholder="密码"
              autoComplete="off"
              rules={[
                {
                  required: true,
                  message: "请输入密码",
                },
              ]}
              onChange={this.changePwdInputType}
              onPressEnter={e => {
                e.preventDefault();
                this.loginForm.validateFields(this.handleSubmit);
              }}
            />
            {isNeedImageCode ? <ImageVerifyCode
              name="imageVerifyCode"
              imageBase64={imageBase64}
              placeholder="请输入验证码"
              onGetImgCode={this.onGetImgCode}
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
              ]}
              onPressEnter={e => {
                e.preventDefault();
                this.loginForm.validateFields(this.handleSubmit);
              }}
            /> : null}


          </Tab>

          <Submit loading={submitting} style={{marginTop: '5px',marginBottom: '60px'}}>
            登录
          </Submit>

          <div className={styles.sysInfo}>
            {/* {verionData&&verionData.hideDownloadClient?null:<a onClick={() => this.downloadBwdaClient()}>下载客户端</a>} */}
            <span>版本号：{verionData&&verionData.productVersion}</span>
          </div>
        </Login>
      </div>
    );
  }
}

export default LoginPage;
